package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单支付超时，执行定时任务
     */
    //@Scheduled(cron = "0 * * * * ?") //每分钟执行一次
    public void payTimeout() {
        log.info("订单超时，执行定时任务");

        // 查询超时订单
        List<Orders> ordersList =orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        for (Orders orders : ordersList) {
            // 如果订单状态为待支付，则修改为已取消
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("订单支付超时");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }
    }

    /**
     * 定时处理处于派送中的订单
     */
    //@Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行一次
    public void deliveryOrder(){
        log.info("定时处理处于派送中的订单");
        // 查询处于派送中的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        // 遍历订单，修改状态为已完成
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        }
    }
}
